import type { AxiosResponse } from 'axios'

export async function downloadFileByResponse(response: AxiosResponse) {
  return new Promise((resolve, reject) => {
    try {
      const blob = response.data
      const contentDisposition = response.headers['content-disposition']
      let fileName = ''

      const matches = contentDisposition.match(/filename\*=utf-8''([^;]*)/)
      if (matches != null && matches[1]) {
        fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''))
      }
      else {
        const matches2 = decodeURIComponent(contentDisposition).match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
        if (matches2 != null && matches2[1]) {
          fileName = matches2[1].replace(/['"]/g, '')
        }
      }
      const a = document.createElement('a')
      const url = URL.createObjectURL(blob)
      a.href = url
      a.download = fileName
      a.click()
      URL.revokeObjectURL(url)

      resolve(true)
    }
    catch (error: any) {
      console.log('error>>>>', error)
      reject(new Error(error?.message ?? '未知错误'))
    }
  })
}
